package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        final String authHeader = request.getHeader("Authorization");
        if (authHeader != null && !"".equals(authHeader)) {
            //如果有包含有Authorization头信息，就对其进行解析
            if (authHeader.startsWith("Bearer ")) {
                //得到token
                final String token = authHeader.substring(7); // The part after "Bearer "
                //对令牌进行解析
                try {
                    Claims claims = jwtUtil.parseJWT(token);//token可能过期，可能找不到，会报错
                    String roles = (String) claims.get("roles");
                    if (roles != null && "admin".equals(roles)) {//如果是管理员
                        request.setAttribute("admin_claims", claims);
                    }
                    if (roles != null &&  "user".equals(roles)) {//如果是用户
                        request.setAttribute("user_claims", claims);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("令牌不正确！");
                }
            }
        }
        return true;
    }
}
